<template>
    <div id="app">
      <div>
        <span>姓名:</span>
        <input type="text" v-model="student.username" />
      </div>
      <div>
        <span>年龄:</span>
        <input type="number" v-model="student.age" />
      </div>
      <div>
        <span>性别:</span>
        <select v-model="student.sex">
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
      <div>
        <button @click="btn">添加/修改</button>
      </div>
      <div>
        <table border="1" cellpadding="10" cellspacing="0">
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
          </tr>
          <tr v-for="(obj,index) in list" :key="index">
            <td>{{index+1}}</td>
            <td>{{obj.username}}</td>
            <td>{{obj.age}}</td>
            <td>{{obj.sex}}</td>
            <td>
              <button @click="del(index)">删除</button>
              <button @click="compile(index)">编辑</button>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </template>
  <script>
  export default {
    data() {
      return {
        student: {
          username: '',
          age: '',
          sex: '',
        },
        list: [],
        isadd: true,
        num:''
      }
    },
    methods: {
      btn() {
        if (!this.isadd) {
            this.list.splice(this.num,1,{...this.student})
            this.isadd=true
        }else{
          this.list.push({ ...this.student })
        this.student.username = ''
        this.student.age = ''
        this.student.sex = ''
        }
      },
      del(ind) {
        this.list.splice(ind, 1)
      },
      compile(ind) {
        this.student = { ...this.list[ind] }
        this.num=ind
        this.isadd=false
      }
    }
  }
  </script>